package com.ymatou.iapi.fastturnover.testcase;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import com.ymatou.iapi.fastturnover.parameter.QueryCanWithdrawAmountReq;
import com.ymatou.iapi.fastturnover.service.QueryCanWithdrawAmountCall;
import com.ymt.core.tool.Logger;
import com.ymt.utils.annotation.TestCase;
import com.ymt.utils.annotation.TestSuite;
import com.ymt.utils.tag.P1;
import com.ymttest.database.model.Account;
import com.ymttest.database.model.biinputdb.SellerLevelHistory;
import com.ymttest.database.model.fastturnover.TurnoverApply;
import com.ymttest.database.sqlwapper.AccountWapper;
import com.ymttest.database.sqlwapper.billinputdb.SellerLevelHistoryWrapper;
import com.ymttest.database.sqlwapper.fastturnover.TurnoverApplyWrapper;
import com.ymttest.utils.DataUtil;
import com.ymttest.utils.TestDataManager;
import com.ymttest.utils.YMTDateUtil;

/**
 * 取消订单 FreeMaker Template自动生成代码
 */
@TestSuite
public class Ts_QueryCanWithdrawAmount {

	private static QueryCanWithdrawAmountReq queryCanWithdrawAmountReq;
	private static QueryCanWithdrawAmountCall queryCanWithdrawAmountCall;
	
	private static SellerLevelHistoryWrapper sellerLevelHistoryWrapper = new SellerLevelHistoryWrapper();
	private static TurnoverApplyWrapper turnoverApplyWrapper = new TurnoverApplyWrapper(); 
	
	private static AccountWapper accountWapper = new AccountWapper();

	@BeforeClass
	public static void setUp() {
		Logger.createResultFile("查询快周转可提现金额");
	}

	@Before
	public void caseUp() {
		queryCanWithdrawAmountReq = new QueryCanWithdrawAmountReq();
		queryCanWithdrawAmountCall = new QueryCanWithdrawAmountCall();
	}

	@AfterClass
	public static void tearDown() {
		Logger.generateResult(queryCanWithdrawAmountCall.getOpurl());
	}

	@After
	public void caseDown() {
		Logger.end();
	}
	
	public void verify(SellerLevelHistory sellerLevelHistory) throws InterruptedException {

		Long sellerId = queryCanWithdrawAmountReq.getSellerId();
		BigDecimal rate = null;
		
		BigDecimal actualResult = new BigDecimal(
				queryCanWithdrawAmountCall.getResult());
		
		Account account = accountWapper.selectAccountInfoByUserId(
				sellerId.intValue(), 1).get(0);
		
		BigDecimal freezeAmount = account.getFreezeAmount();
		BigDecimal unconfirmAmount = sellerLevelHistory.getUnconfirm_amount();
		BigDecimal availAmount = account.getAvailAmount();
		
		List<TurnoverApply> turnoverApplys = turnoverApplyWrapper.selectBySellerId(sellerId);
		
		// 最近180天快周转完成次数
		List<TurnoverApply> latestTurnoverApplys = turnoverApplys
				.stream()
				.filter(apply -> apply.getPay_status() == 1
						&& YMTDateUtil.diffDay(YMTDateUtil.getDate(),
								apply.getAdd_time()) <= 180)
				.collect(Collectors.toList());
		
		if (latestTurnoverApplys.size() >= 3) {
			
			long diffRepaymentHour = 0;
			
			for (TurnoverApply turnoverApply : latestTurnoverApplys) {
				
				diffRepaymentHour = diffRepaymentHour
						+ YMTDateUtil.diffHour(turnoverApply.getRepay_time(),
								turnoverApply.getAdd_time());
			}
			
			long avgDiffRepaymentHour = diffRepaymentHour / latestTurnoverApplys.size();
			
			if (avgDiffRepaymentHour <= 240)
				rate = new BigDecimal("0.80");
			else if (240 < avgDiffRepaymentHour && avgDiffRepaymentHour <= 480)
				rate = new BigDecimal("0.70");
			else
				rate = new BigDecimal("0.60");
			
		} else {
			
			rate = new BigDecimal("0.60");
		}
		
		BigDecimal expectResult = (availAmount.subtract(freezeAmount)
				.add(unconfirmAmount)).multiply(rate).setScale(2,
				BigDecimal.ROUND_HALF_UP);
		
		DataUtil.verifyDecimalEquals(expectResult, actualResult, "验证可提现金额");
	}

	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_QueryCanWithdrawAmount_001() {
		Logger.start(true, "查询可提现金额, 费率60%");
		try {
			// 创建订单
			Logger.comment("前置数据准备");
			
			Long sellerId = 24635724L;
			
			SellerLevelHistory sellerLevelHistory = sellerLevelHistoryWrapper.selectByDDateAndSellerId(
					YMTDateUtil.getFormatDateString(YMTDateUtil.getDate(),
							YMTDateUtil.YMD), sellerId);
			
			// 如果没有当天的在途结算金额
			if (sellerLevelHistory == null) {
				
				sellerLevelHistory = new SellerLevelHistory();

				sellerLevelHistory.setDDate(YMTDateUtil.getDate());
				sellerLevelHistory.setSellerID(sellerId.intValue());
				sellerLevelHistory.setUpdateTime(YMTDateUtil.getDate());
				sellerLevelHistory.setUnconfirm_amount(BigDecimal.TEN);
				
				sellerLevelHistoryWrapper.insertSelective(sellerLevelHistory);
			}
			
			queryCanWithdrawAmountReq.setSellerId(24635724L);

			// 发送请求
			queryCanWithdrawAmountCall.setData(queryCanWithdrawAmountReq);
			queryCanWithdrawAmountCall.callService();
			Logger.verifyEquals(200, queryCanWithdrawAmountCall.getRetultCode(),
					"验证Code");

			// 数据库验证
			verify(sellerLevelHistory);

		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	
	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_QueryCanWithdrawAmount_002() {
		Logger.start(true, "查询买手在途数据失败");
		try {
			// 创建订单
			Logger.comment("前置数据准备");

			queryCanWithdrawAmountReq.setSellerId(3333L);

			// 发送请求
			queryCanWithdrawAmountCall.setData(queryCanWithdrawAmountReq);
			queryCanWithdrawAmountCall.callService();
			
			Logger.verifyEquals(202, queryCanWithdrawAmountCall.getRetultCode(),
					"验证Code");
			Logger.verifyIsContains("在途数据失败", queryCanWithdrawAmountCall.getMsg(),
					"验证Msg");

		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	
	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_QueryCanWithdrawAmount_003() {
		Logger.start(true, "获取买手账户余额信息失败");
		try {
			// 创建订单
			Logger.comment("前置数据准备");

			queryCanWithdrawAmountReq.setSellerId(311133223L);

			// 发送请求
			queryCanWithdrawAmountCall.setData(queryCanWithdrawAmountReq);
			queryCanWithdrawAmountCall.callService();
			
			Logger.verifyEquals(202, queryCanWithdrawAmountCall.getRetultCode(),
					"验证Code");
			Logger.verifyEquals("获取买手账户余额信息失败", queryCanWithdrawAmountCall.getMsg(),
					"验证Msg");

		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	
	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_QueryCanWithdrawAmount_004() {
		Logger.start(true, "查询可提现金额, 费率70%");
		try {
			// 创建订单
			Logger.comment("前置数据准备");
			
			Long sellerId = 24635724L;
			
			SellerLevelHistory sellerLevelHistory = sellerLevelHistoryWrapper.selectByDDateAndSellerId(
					YMTDateUtil.getFormatDateString(YMTDateUtil.getDate(),
							YMTDateUtil.YMD), sellerId);
			
			// 如果没有当天的在途结算金额
			if (sellerLevelHistory == null) {
				
				sellerLevelHistory = new SellerLevelHistory();

				sellerLevelHistory.setDDate(YMTDateUtil.getDate());
				sellerLevelHistory.setSellerID(sellerId.intValue());
				sellerLevelHistory.setUpdateTime(YMTDateUtil.getDate());
				sellerLevelHistory.setUnconfirm_amount(BigDecimal.TEN);
				
				sellerLevelHistoryWrapper.insertSelective(sellerLevelHistory);
			}
			
			// 插入快周转完成次数3次，且最近180天平均还款失效大于240小时，小于等于480小时
			for (int i = 0; i < 3; i++) {
				
				TurnoverApply turnoverApply = new TurnoverApply();
				
				Date today = YMTDateUtil.getDate();
				
				turnoverApply.setApply_no("autotest" + TestDataManager.getRandomIntNum(10));
				turnoverApply.setApply_total_amount(BigDecimal.ONE);
				turnoverApply.setWithdraw_currency(1);
				turnoverApply.setSeller_id(sellerId);
				turnoverApply.setPay_status(1);
				turnoverApply.setRepay_status(1);
				turnoverApply.setRepay_time(YMTDateUtil.getBeforeOrNextHour(today, 241));
				turnoverApply.setAdd_time(today);
				turnoverApply.setUpdate_time(today);
				
				
				turnoverApplyWrapper.insertSelective(turnoverApply);
			}
			
			queryCanWithdrawAmountReq.setSellerId(24635724L);

			// 发送请求
			queryCanWithdrawAmountCall.setData(queryCanWithdrawAmountReq);
			queryCanWithdrawAmountCall.callService();
			Logger.verifyEquals(200, queryCanWithdrawAmountCall.getRetultCode(),
					"验证Code");

			// 数据库验证
			verify(sellerLevelHistory);
			
			// 删除垃圾数据
			turnoverApplyWrapper.deleteByApplyNoAndSellerId("autotest", sellerId);

		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	
	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_QueryCanWithdrawAmount_005() {
		Logger.start(true, "查询可提现金额, 费率80%");
		try {
			// 创建订单
			Logger.comment("前置数据准备");
			
			Long sellerId = 24635724L;
			
			SellerLevelHistory sellerLevelHistory = sellerLevelHistoryWrapper.selectByDDateAndSellerId(
					YMTDateUtil.getFormatDateString(YMTDateUtil.getDate(),
							YMTDateUtil.YMD), sellerId);
			
			// 如果没有当天的在途结算金额
			if (sellerLevelHistory == null) {
				
				sellerLevelHistory = new SellerLevelHistory();

				sellerLevelHistory.setDDate(YMTDateUtil.getDate());
				sellerLevelHistory.setSellerID(sellerId.intValue());
				sellerLevelHistory.setUpdateTime(YMTDateUtil.getDate());
				sellerLevelHistory.setUnconfirm_amount(BigDecimal.TEN);
				
				sellerLevelHistoryWrapper.insertSelective(sellerLevelHistory);
			}
			
			// 插入快周转完成次数3次，且最近180天平均还款失效小于等于240小时
			for (int i = 0; i < 3; i++) {
				
				TurnoverApply turnoverApply = new TurnoverApply();
				
				Date today = YMTDateUtil.getDate();
				
				turnoverApply.setApply_no("autotest" + TestDataManager.getRandomIntNum(10));
				turnoverApply.setApply_total_amount(BigDecimal.ONE);
				turnoverApply.setWithdraw_currency(1);
				turnoverApply.setSeller_id(sellerId);
				turnoverApply.setPay_status(1);
				turnoverApply.setRepay_status(1);
				turnoverApply.setRepay_time(YMTDateUtil.getBeforeOrNextHour(today, 239));
				turnoverApply.setAdd_time(today);
				turnoverApply.setUpdate_time(today);
				
				
				turnoverApplyWrapper.insertSelective(turnoverApply);
			}
			
			queryCanWithdrawAmountReq.setSellerId(24635724L);

			// 发送请求
			queryCanWithdrawAmountCall.setData(queryCanWithdrawAmountReq);
			queryCanWithdrawAmountCall.callService();
			Logger.verifyEquals(200, queryCanWithdrawAmountCall.getRetultCode(),
					"验证Code");

			// 数据库验证
			verify(sellerLevelHistory);
			
			// 删除垃圾数据
			turnoverApplyWrapper.deleteByApplyNoAndSellerId("autotest",
					sellerId);

		} catch (Exception e) {
			Logger.fail(e);
		}
	}
}
